package com.leyou.auth.service.impl;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.AuthUserService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.auth.constants.JwtConstants.*;

@Service
public class AuthUserServiceImpl implements AuthUserService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void userLogin(String username, String password, HttpServletResponse response) {

        //通过feign请求user-service如果没有拿到userDTO抛异常
        UserDTO userDTO = null;
        try {
            userDTO = this.userClient.queryUser(username, password);
        } catch (FeignException e) {
            new LyException(e.status(), e.getMessage());
        }

        UserDetail userDetail = UserDetail.of(userDTO.getId(), userDTO.getUsername());

        //生成token
        String token = jwtUtils.createJwt(userDetail);

        //创建cookie
        Cookie cookie = new Cookie("LY_TOKEN", token);
        //绑定的域名
        cookie.setDomain("leyou.com");
        //当前域下的适配路径
        cookie.setPath("/");
        //对前端的script技术隐藏，提升安全性
        cookie.setHttpOnly(true);

        response.addCookie(cookie);
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {

        //删除redis中的jti
        try {
            String token = CookieUtils.getCookieValue(request, COOKIE_NAME);

            Payload payload = jwtUtils.parseJwt(token);

            UserDetail userDetail = payload.getUserDetail();

            String key = KEY_PREFIX + userDetail.getUsername();

            this.redisTemplate.delete(key);

        } catch (Exception e) {
        }

        //重新生成cookie，覆盖之前的
        Cookie cookie = new Cookie(COOKIE_NAME, "");
        cookie.setDomain(DOMAIN);

        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

    }
}
